package com.youdianstar.app.common.network

import android.util.Log
import com.youdianstar.app.common.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit


/**
 * File: BaseNetworkApi
 * Author: 82149 Create: 2021/9/18 11:24
 * Changes (from 2021/9/18)
 * --------------------------------------------------
 * description: 子Module可以使用后续重写的NetworkApi,也可自己重写; 为什么不用动态替换Url? 还在摸索中,后续吧
 * 本项目抛弃Rxjava. 采用 协程+Retrofit+Okhttp为网络请求框架;
 * 主要分为UI、ViewModel、Repository三层，以LiveData为媒介进行通信
 * ---------------------------------------------------
 *
 */
abstract class BaseNetworkApi {
    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，Protocol
     */
    abstract fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder

    /**
     * 实现重写父类的setHttpClientBuilder方法，
     * 在这里可以添加拦截器，可以对 OkHttpClient.Builder 做任意操作
     */
    abstract fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder

    /**
     * 获取OkHttpClient
     */
    abstract fun getOkHttpClient():OkHttpClient


    fun <T> getApi(serviceClass: Class<T>, baseUrl: String): T {
        val retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(getOkHttpClient())
        return setRetrofitBuilder(retrofitBuilder).build().create(serviceClass)
    }


    /**基本构建样例*/
    fun getBaseClient(): OkHttpClient.Builder {
        return OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(25, TimeUnit.SECONDS)
            .writeTimeout(25, TimeUnit.SECONDS)
            .callTimeout(30, TimeUnit.SECONDS) //总超时时间
            .retryOnConnectionFailure(true)
            .followRedirects(false)
            .cookieJar(LocalCookieJar.getInstance())
            .addInterceptor(HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
                override fun log(message: String) {
                    Log.d("BaseNetworkApi", "log: $message")
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY))
    }


    fun loggingInterceptor() =
        HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor.Level.BODY
            } else {
                HttpLoggingInterceptor.Level.NONE
            }
        }
}